{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "import os\n",
    "# option to import from github folder\n",
    "sys.path.insert(0, 'C:/Users/carse/github/suite2p')\n",
    "import suite2p\n",
    "from suite2p.run_s2p import run_s2p\n",
    "\n",
    "ops = {\n",
    "        # file paths\n",
    "        'look_one_level_down': False, # whether to look in all subfolders when searching for tiffs\n",
    "        'fast_disk': [], # used to store temporary binary file, defaults to save_path0\n",
    "        'delete_bin': False, # whether to delete binary file after processing\n",
    "        'h5py_key': 'data', # key in h5 where data array is stored (data should be time x pixels x pixels)\n",
    "        # main settings\n",
    "        'nplanes' : 12, # each tiff has these many planes in sequence\n",
    "        'nchannels' : 2, # each tiff has these many channels per plane\n",
    "        'functional_chan' : 1, # this channel is used to extract functional ROIs (1-based)\n",
    "        'diameter':12, # this is the main parameter for cell detection, 2-dimensional if Y and X are different (e.g. [6 12])\n",
    "        'tau':  2., # this is the main parameter for deconvolution\n",
    "        'fs': 2.5,  # sampling rate (total across planes)\n",
    "        # output settings\n",
    "        'save_mat': False, # whether to save output as matlab files\n",
    "        'combined': False, # combine multiple planes into a single result /single canvas for GUI\n",
    "        # parallel settings\n",
    "        'num_workers': 0, # 0 to select num_cores, -1 to disable parallelism, N to enforce value\n",
    "        'num_workers_roi': -1, # 0 to select number of planes, -1 to disable parallelism, N to enforce value\n",
    "        # registration settings\n",
    "        'do_registration': True, # whether to register data\n",
    "        'nimg_init': 200, # subsampled frames for finding reference image\n",
    "        'batch_size': 200, # number of frames per batch\n",
    "        'maxregshift': 0.1, # max allowed registration shift, as a fraction of frame max(width and height)\n",
    "        'align_by_chan' : 1, # when multi-channel, you can align by non-functional channel (1-based)\n",
    "        'reg_tif': False, # whether to save registered tiffs\n",
    "        'subpixel' : 10, # precision of subpixel registration (1/subpixel steps)\n",
    "        # cell detection settings\n",
    "        'connected': True, # whether or not to keep ROIs fully connected (set to 0 for dendrites)\n",
    "        'navg_frames_svd': 5000, # max number of binned frames for the SVD\n",
    "        'nsvd_for_roi': 1000, # max number of SVD components to keep for ROI detection\n",
    "        'max_iterations': 20, # maximum number of iterations to do cell detection\n",
    "        'ratio_neuropil': 6., # ratio between neuropil basis size and cell radius\n",
    "        'ratio_neuropil_to_cell': 3, # minimum ratio between neuropil radius and cell radius\n",
    "        'tile_factor': 1., # use finer (>1) or coarser (<1) tiles for neuropil estimation during cell detection\n",
    "        'threshold_scaling': 1., # adjust the automatically determined threshold by this scalar multiplier\n",
    "        'max_overlap': 0.75, # cells with more overlap than this get removed during triage, before refinement\n",
    "        'inner_neuropil_radius': 2, # number of pixels to keep between ROI and neuropil donut\n",
    "        'outer_neuropil_radius': np.inf, # maximum neuropil radius\n",
    "        'min_neuropil_pixels': 350, # minimum number of pixels in the neuropil\n",
    "        # deconvolution settings\n",
    "        'baseline': 'maximin', # baselining mode\n",
    "        'win_baseline': 60., # window for maximin\n",
    "        'sig_baseline': 10., # smoothing constant for gaussian filter\n",
    "        'prctile_baseline': 8.,# optional (whether to use a percentile baseline)\n",
    "        'neucoeff': .7,  # neuropil coefficient\n",
    "        'allow_overlap': False,\n",
    "        'xrange': np.array([0, 0]),\n",
    "        'yrange': np.array([0, 0]),\n",
    "      }\n",
    "\n",
    "# provide an h5 path in 'h5py' or a tiff path in 'data_path'\n",
    "# db overwrites any ops (allows for experiment specific settings)\n",
    "db = {\n",
    "      'h5py': [], # a single h5 file path\n",
    "      'h5py_key': 'data',\n",
    "      'look_one_level_down': False, # whether to look in ALL subfolders when searching for tiffs\n",
    "      'data_path': ['C:/Users/carse/TIFFS'], # a list of folders with tiffs \n",
    "                                             # (or folder of folders with tiffs if look_one_level_down is True, or subfolders is not empty)\n",
    "      'subfolders': [] # choose subfolders of 'data_path' to look in (optional)\n",
    "    }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### RUN PIPELINE ON FIRST CHANNEL\n",
    "opsEnd=run_s2p(ops=ops,db=db)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### SETUP FOR RUNNING ONLY CELL DETECTION ON SECOND CHANNEL\n",
    "import shutil\n",
    "\n",
    "# grab fast_disk variable if it is user-specified\n",
    "if 'fast_disk' in ops and len(ops['fast_disk'])>0:\n",
    "    fast_disk = ops['fast_disk']\n",
    "else:\n",
    "    fast_disk = []\n",
    "# grab save_path0\n",
    "save_path0 = opsEnd[0]['save_path0']\n",
    "# make a new folder for channel 2 save files and binary files\n",
    "ops1 = []\n",
    "j=0\n",
    "for ops in opsEnd:\n",
    "    # make a chan2 folder inside the save path\n",
    "    ops['save_path0'] = os.path.join(save_path0,'chan2')\n",
    "    ops['save_path'] = os.path.join(ops['save_path0'], 'suite2p', 'plane%d'%j)\n",
    "    os.makedirs(ops['save_path'], exist_ok=True)\n",
    "    ops['ops_path'] = os.path.join(ops['save_path'],'ops.npy')\n",
    "    # put binary file there or in user-specified + chan2\n",
    "    if len(fast_disk)==0:\n",
    "        fast_disk0 = os.path.join(ops['save_path0'])\n",
    "    else:\n",
    "        fast_disk0 = os.path.join(fast_disk0,'chan2')\n",
    "    ops['fast_disk'] = os.path.join(fast_disk0, 'suite2p', 'plane%d'%j)\n",
    "    os.makedirs(ops['fast_disk'], exist_ok=True)\n",
    "    ops['reg_file'] = os.path.join(ops['fast_disk'], 'data.bin')\n",
    "    # switch meanImg <-> meanImg_chan2\n",
    "    mimg = ops['meanImg']\n",
    "    ops['meanImg'] = ops['meanImg_chan2']\n",
    "    ops['meanImg_chan2'] = mimg\n",
    "    # copy chan2 reg file to new location\n",
    "    shutil.copyfile(ops['reg_file_chan2'], ops['reg_file'])\n",
    "    print('reg_file_chan2 copied to %s'%(ops['reg_file']))\n",
    "    # save new ops file with paths\n",
    "    np.save(ops['ops_path'], ops)\n",
    "    ops1.append(ops.copy())\n",
    "    j+=1\n",
    "# save ops across planes in new location\n",
    "np.save(os.path.join(ops1[0]['save_path0'],'suite2p','ops1.npy'), ops1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# run pipeline on second channel \n",
    "# (will skip registration b/c binary file exists)\n",
    "ops0 = ops1[0].copy()\n",
    "del ops0['save_path']\n",
    "del ops0['ops_path']\n",
    "del ops0['reg_file']\n",
    "del ops0['reg_file_chan2']\n",
    "\n",
    "opsEnd=run_s2p(ops=ops0,db=db)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
